import { Component, OnInit, Input, Output, forwardRef, EventEmitter, SimpleChanges } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzImageService} from 'ng-zorro-antd/image';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { CommonService } from '../../../services-common/common.service';
import { defalutImg } from '../../../comm';

interface limitTypes {
  nzSize?: number,
  nzFileType?: string
}

@Component({
  selector: 'zdy-upload',
  templateUrl: './upload-imgs.component.html',
  styleUrls: ['./upload-imgs.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UploadImgsComponent),
      multi: true
    }
  ]
})
export class UploadImgsComponent implements ControlValueAccessor, OnInit {

  @Input() uploadSize: number | string = 120; // 上传组件大小
  @Input() limitSize: number | string = 1; // 上传数、默认1张
  @Input() uploadFileName: string = 'uploadFile'; // 图片上传参数（上传文件名）
  @Input() multiple: boolean = false; // 多张 | 单张
  @Input() disabled: boolean = false; // 禁用
  @Input() isDrag: boolean = false; // 是否可拖拽
  @Input() limitParams: limitTypes = {
    nzSize: 0,
    nzFileType: 'image/*'
  };
  @Input() beforeUpload?: (file: NzUploadFile) => boolean | Observable<boolean>;
  @Input() isUploadAliyun: boolean = false; // 是否上传阿里云地址

  @Output() uploadImgChange: any = new EventEmitter();

  fallback: string = defalutImg;
  uploadLoading: boolean = false;

  imgLists: Array<any> = [];
  onChange: any = () => {};

  /**
   * SortTable Imgs
   * ----------------------------------------------------------------
   */
  isStartSort = false;
  sortablejsOptions = {
    animation: 200,
    handle: '.handle-sort',
    filter: '.filter-sort', // 不需要拖动的元素
    onStart: () => {
      // 开始拖拽
      setTimeout(() => {
        this.isStartSort = true;
      })
    },
    onEnd: () => {
      // 拖拽结束
      setTimeout(() => {
        this.isStartSort = false;
      })
    }
  }

  constructor(
    private message: NzMessageService,
    private nzImageService: NzImageService,
    private commonService: CommonService
  ) { }

  ngOnInit(): void {
  }

  writeValue(val: any) {
    let valType = Object.prototype.toString.call(val);
    this.imgLists = (this.multiple && valType === '[object Array]') ? val : (val ? val.split(',') : []);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    // this.onTouched = fn;
  }

  /**
   * 自定义上传
   * @param options 
   */
  uploadCustomRequest = (options: any): any => {
    const {file} = options;
    this.uploadInterface(file);
  }

  /**
   * @description: Upload Interface
   * @param {File} file
   * @return
   */
  async uploadInterface(file: File) {
    // if (!file || this.uploadLoading) {
    //   return
    // }

    this.uploadLoading = true;
    let res: any = null;
    if (this.isUploadAliyun) {
      // 上传至阿里云
      res = await this.commonService.uploadAliyunFileData(file, '');
    } else {
      // 上传至商城服务
      res = await this.commonService.uploadFileData(file, this.uploadFileName);
    }
    this.uploadLoading = false;

    if (res.code == 0) {
      this.message.success('图片上传成功');
      let backupsImgs = JSON.parse(JSON.stringify(this.imgLists));
      this.imgLists = [];
      setTimeout(() => {
        this.imgLists = backupsImgs.concat([res.data]);
        
        let tempVal = this.multiple ? this.imgLists : this.imgLists.join(',');
        this.onChange(tempVal);
        this.uploadImgChange.emit(tempVal);
      })
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * @description: Delete Img
   * @param {number} index
   * @return
   */  
  deleteImg(index: number) {
    // this.imgLists.splice(index, 1);
    this.imgLists = this.imgLists.filter((ele, i) => i !== index);

    let tempVal = this.multiple ? this.imgLists : this.imgLists.join(',');
    this.onChange(tempVal);
    this.uploadImgChange.emit(tempVal);
  }

  /**
   * @description: Preview
   * @param {*}
   * @return
   */  
  showImgsCarousel(url: any, index: number) {
    let previewArrs = this.imgLists.length > 1 ? this.imgLists.slice(index).concat(this.imgLists.slice(0, index)) : this.imgLists;
    let images = previewArrs.map((imgUrl: any) => {
      return {
        src: imgUrl,
        alt: '预览图'
      }
    })
    
    this.nzImageService.preview(images, {
      nzZoom: 1.5,
      nzRotate: 0
    });
  }
}
